package com.irdstudio.efp.esb.api.rest.yed.repay;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.constant.ESBConstant;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.constant.SDicCertTypeEnum;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.rest.yed.req.ReqRepayRecordYedBean;
import com.irdstudio.efp.esb.api.rest.yed.resp.AccLoanArr;
import com.irdstudio.efp.esb.api.rest.yed.resp.RepayDetailArr;
import com.irdstudio.efp.esb.api.rest.yed.resp.RespRepayRecordYedBean;
import com.irdstudio.efp.esb.api.service.sed.SedCommonService;
import com.irdstudio.efp.esb.api.service.yed.YedRepayDetailService;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.constant.RespRetCode;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.esb.service.bo.req.hj.RepayInfoQueryReqBean;
import com.irdstudio.efp.esb.service.bo.resp.hj.RepayInfoQueryRespBean;
import com.irdstudio.efp.esb.service.facade.hj.RepayInfoQueryService;
import com.irdstudio.efp.loan.service.facade.AccLoanService;
import com.irdstudio.efp.loan.service.facade.LoanRepayDetailService;
import com.irdstudio.efp.loan.service.vo.AccLoanVO;
import com.irdstudio.efp.loan.service.vo.LoanRepayDetailVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 需求编号：xxxxxx<br/>
 * 问题编号：<br/>
 * 功能描述：优e贷还款记录查询<br/>
 * 创建时间：2020/8/7 10:37
 *
 * @Author tiankg
 * @Version 1.0
 * @Since 1.0
 */
@RestController
@RequestMapping("/esb")
public class YedRepayRecordController implements FrameworkService {

    private static Logger logger = LoggerFactory.getLogger(YedRepayRecordController.class);

    @Autowired
    private SedCommonService<RespRepayRecordYedBean> sedCommonService;

    @Autowired
    private YedRepayDetailService yedRepayDetailService;

    @Autowired
    @Qualifier("loanRepayDetailService")
    private LoanRepayDetailService loanRepayDetailService;

    @Autowired
    private RepayInfoQueryService repayInfoQueryService;

    @Autowired
    private AccLoanService accLoanService;

    /**
     * 获取ESB请求对象，校验 ESB请求系统头和请求应用头对象
     *
     * @param request 请求对象集合
     * @return
     */
    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("校验 ESB请求系统头和请求应用头对象!");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    /**
     * 获取ESB请求对象，校验 ESB请求体对象
     *
     * @param request 请求对象集合
     * @return
     */
    @ModelAttribute("reqRepayRecordYedBean")
    public ReqRepayRecordYedBean getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("校验 ESB请求体对象！");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, ReqRepayRecordYedBean.class);
    }

    @PostMapping("/SERVICE_30230002_10")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
                                     @Validated @ModelAttribute("reqRepayRecordYedBean") ReqRepayRecordYedBean reqRepayRecordYedBean, BindingResult br2, Exception exception) throws ESBException {
        //全局流水
        String glblSrlNo = esbReqServiceBean.getSysHead().getGlblSrlNo();
        logger.info("还款明细查询开始,全局流水号为：[{}]", glblSrlNo);
        //页码-当前查询第几页的数据
        String pageNo = reqRepayRecordYedBean.getPageNo();
        //每页显示条数
        String pageSize = reqRepayRecordYedBean.getPageSize();
        //产品编号
        String prdCode = reqRepayRecordYedBean.getPdNo();
        //身份证号
        String certCode = reqRepayRecordYedBean.getIdCardNo();
        //证件类型：身份证
        String certType = SDicCertTypeEnum.IDCARD.getValue();
        //响应体
        RespRepayRecordYedBean respRepayRecordYedBean = new RespRepayRecordYedBean();

        if (Objects.nonNull(exception)) {
            //如果异常不为空，那么处理异常返回信息
            return sedCommonService.getEsbRespServiceBeanByException(esbReqServiceBean, exception, respRepayRecordYedBean, RespRetCode.FAILE, EsbRetCodeStandard.JKYDCSJYBTG);
        }

        try {
            //根据产品编号和身份证号查询相关的借据信息
            AccLoanVO loanQueryParam = new AccLoanVO();
            loanQueryParam.setPrdCode(prdCode);
            loanQueryParam.setCertCode(certCode);
            loanQueryParam.setCertType(certType);
            List<AccLoanVO> accLoanVOList1 = accLoanService.queryByCertandPrd(loanQueryParam);
            loanQueryParam.setPage(Integer.parseInt(pageNo));
            loanQueryParam.setSize(Integer.parseInt(pageSize));
            List<AccLoanVO> accLoanVOList = accLoanService.queryByCertAndPrdByPage(loanQueryParam);
            if (accLoanVOList.size() < 1) {//台账表中没有查到借据信息
                return sedCommonService.getSucessBean(esbReqServiceBean, respRepayRecordYedBean, RespRetCode.SUCCESS);
            }

            List<AccLoanArr> accLoanArrs = new ArrayList<AccLoanArr>();
            for (AccLoanVO accLoanVO:accLoanVOList){//遍历某产品下借据
                ArrayList<RepayDetailArr> repayDetailArrs = new ArrayList<>();
                //根据借据号查询借据在网贷系统的还款明细
                List<LoanRepayDetailVO> loanRepayDetailVOS = new ArrayList<LoanRepayDetailVO>();
                LoanRepayDetailVO queryLoanRepayDetailVO = new LoanRepayDetailVO();
                queryLoanRepayDetailVO.setLoanNo(accLoanVO.getBillNo());
                loanRepayDetailVOS = loanRepayDetailService.queryAllByLoanNoByPage(queryLoanRepayDetailVO);

                    //根据贷款号发放号查询互金的还款明细
                    RepayInfoQueryReqBean repayInfoQueryReqBean = new RepayInfoQueryReqBean();
                    repayInfoQueryReqBean.setLoanNo(accLoanVO.getLoanSeq());
                    repayInfoQueryReqBean.setDistrNo(accLoanVO.getDistrNo());
                    repayInfoQueryReqBean.setGlobaNo(glblSrlNo);
    //              repayInfoQueryReqBean.setRpyNo(loanRepayDetailVOS.get(0).getRpyNo());//根据还款号查询记录
                    RepayInfoQueryRespBean repayInfoQueryRespBean = repayInfoQueryService.applyRepayInfoQuery(repayInfoQueryReqBean);
                    //封装响应报文
                    yedRepayDetailService.yedhandleResp(accLoanArrs,repayDetailArrs,loanRepayDetailVOS, accLoanVO, repayInfoQueryRespBean);

            }
            respRepayRecordYedBean.setPageNo(pageNo);
            respRepayRecordYedBean.setPagSize(pageSize);
            respRepayRecordYedBean.setTotalSize(accLoanVOList1.size() <= 0 ? "0" : String.valueOf(accLoanVOList1.size()));
            respRepayRecordYedBean.setAccLoanArr(accLoanArrs);
            respRepayRecordYedBean.setRetCd(ESBConstant.SUCCESS);
            respRepayRecordYedBean.setRetMsg("查询成功");
            //返回报文
            return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean,
                    JSONObject.toJSONString(respRepayRecordYedBean, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteMapNullValue),
                    EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(),
                    EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(),
                    "查询成功");

        } catch (Exception ex) {
            logger.error("还款明细接口出现异常，异常信息为：", ex.getMessage());
            ex.printStackTrace();
            return sedCommonService.getEsbRespServiceBeanByException(esbReqServiceBean, ex, respRepayRecordYedBean, RespRetCode.FAILE, EsbRetCodeStandard.SJCLYC);
        }
    }

}
